package org.keyyond.ms.core.util;

import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Encryption {
	byte[] encryptKey;
	DESedeKeySpec spec;
	SecretKeyFactory keyFactory;
	SecretKey theKey;
	Cipher cipher;
	IvParameterSpec IvParameters;

	public static void main(String[] args) {
		// System.out.println(new
		// Encryption().decrypt(URLDecoder.decode("%2BQTNL7hTaHUmsuYt%2FOrMCQ%3D%3D")));
		System.out.println(new Encryption().encrypt("18918526936"));
		System.out.println(new Encryption().encrypt("123asd!@#"));
		// "cmWSKAbR2XglpQpL5CwmlA%3D%3D"
		System.out.println(URLDecoder.decode("Ikm+M/CKtjFrZA4ZGDS/TA=="));
		System.out.println(new Encryption().decrypt(URLDecoder.decode("rudEu9BoLRk%3D")));
	}

	public Encryption() {
		try {
			try {
				Cipher c = Cipher.getInstance("DESede");
			} catch (Exception e) {
				System.err.println("Installling SunJCE provider.");
			}

			this.encryptKey = "Shanghai Chinaccs DESede Key".getBytes();

			this.spec = new DESedeKeySpec(this.encryptKey);

			this.keyFactory = SecretKeyFactory.getInstance("DESede");

			this.theKey = this.keyFactory.generateSecret(this.spec);

			this.cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");

			this.IvParameters = new IvParameterSpec(new byte[] { 12, 34, 56,
					78, 90, 87, 65, 43 });
		} catch (Exception exc) {
			exc.printStackTrace();
		}
	}

	public String encrypt(String password) {
		String encrypted_password = null;
		byte[] encrypted_pwd = (byte[]) null;
		BASE64Encoder encoder = new BASE64Encoder();
		try {
			this.cipher.init(1, this.theKey, this.IvParameters);

			byte[] plainttext = password.getBytes();

			encrypted_pwd = this.cipher.doFinal(plainttext);

			encrypted_password = new String(encoder.encode(encrypted_pwd));

			System.out.println(encoder.encode(encrypted_pwd));
		} catch (Exception ex) {
			System.out.println(" 记录加密错误");
			encrypted_password = "";
		}

		String newString = "";
		newString = URLEncoder.encode(encrypted_password);
		return newString;
	}

	public String decrypt(String encrystr) {
		String decrypted_password = null;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte[] password = decoder.decodeBuffer(deconbase64(encrystr));

			this.cipher.init(2, this.theKey, this.IvParameters);

			byte[] decryptedPassword = password;

			byte[] decrypted_pwd = this.cipher.doFinal(decryptedPassword);

			decrypted_password = new String(decrypted_pwd);
		} catch (Exception localException) {
		}

		return decrypted_password;
	}

	public static String conbase64(String sencode) {
		return sencode;
	}

	public static String deconbase64(String sencode) {
		return sencode;
	}
}